/**
 * Hero项目登录模态框组件
 * 
 * 提供登录、注册、注销确认等模态框功能
 * 支持登录状态过期自动弹出提示
 * 
 * 使用方式：
 * ```html
 * <link rel="stylesheet" href="css/login-modal.css">
 * <script src="js/auth.js"></script>
 * <script src="js/login-modal.js"></script>
 * <script>
 *     // 显示登录模态框
 *     HeroLoginModal.showLogin();
 *     
 *     // 显示注册模态框
 *     HeroLoginModal.showRegister();
 *     
 *     // 显示注销确认模态框
 *     HeroLoginModal.showLogoutConfirm();
 *     
 *     // 显示登录过期模态框
 *     HeroLoginModal.showExpiredModal();
 * </script>
 * ```
 */

(function() {
    
    // 创建模态框HTML结构
    function createModalHTML() {
        return `
            <!-- 登录模态框 -->
            <div id="hero-login-modal" class="hero-modal">
                <div class="hero-modal-content">
                    <div class="hero-modal-header">
                        <h2>用户登录</h2>
                        <span class="hero-modal-close">&times;</span>
                    </div>
                    <div class="hero-modal-body">
                        <form id="hero-login-form">
                            <div class="hero-form-group">
                                <label for="login-username">用户名</label>
                                <input type="text" id="login-username" name="username" required>
                            </div>
                            <div class="hero-form-group">
                                <label for="login-password">密码</label>
                                <input type="password" id="login-password" name="password" required>
                            </div>
                            <div class="hero-form-actions">
                                <button type="submit" class="hero-btn hero-btn-primary">登录</button>
                                <button type="button" class="hero-btn hero-btn-link" id="show-register">注册账号</button>
                            </div>
                        </form>
                        <div id="login-message" class="hero-message"></div>
                    </div>
                </div>
            </div>
            
            <!-- 注册模态框 -->
            <div id="hero-register-modal" class="hero-modal">
                <div class="hero-modal-content">
                    <div class="hero-modal-header">
                        <h2>用户注册</h2>
                        <span class="hero-modal-close">&times;</span>
                    </div>
                    <div class="hero-modal-body">
                        <form id="hero-register-form">
                            <div class="hero-form-group">
                                <label for="reg-username">用户名</label>
                                <input type="text" id="reg-username" name="username" required>
                            </div>
                            <div class="hero-form-group">
                                <label for="reg-password">密码</label>
                                <input type="password" id="reg-password" name="password" required>
                            </div>
                            <div class="hero-form-group">
                                <label for="reg-confirm-password">确认密码</label>
                                <input type="password" id="reg-confirm-password" name="confirmPassword" required>
                            </div>
                            <div class="hero-form-actions">
                                <button type="submit" class="hero-btn hero-btn-primary">注册</button>
                                <button type="button" class="hero-btn hero-btn-link" id="show-login">已有账号？登录</button>
                            </div>
                        </form>
                        <div id="register-message" class="hero-message"></div>
                    </div>
                </div>
            </div>
            
            <!-- 注销确认模态框 -->
            <div id="hero-logout-modal" class="hero-modal">
                <div class="hero-modal-content hero-modal-small">
                    <div class="hero-modal-header">
                        <h2>确认注销</h2>
                        <span class="hero-modal-close">&times;</span>
                    </div>
                    <div class="hero-modal-body">
                        <p>您确定要注销登录吗？</p>
                        <div class="hero-form-actions">
                            <button type="button" class="hero-btn hero-btn-danger" id="confirm-logout">确认注销</button>
                            <button type="button" class="hero-btn hero-btn-secondary" id="cancel-logout">取消</button>
                        </div>
                        <div id="logout-message" class="hero-message"></div>
                    </div>
                </div>
            </div>
            
            <!-- 登录过期模态框 -->
            <div id="hero-expired-modal" class="hero-modal">
                <div class="hero-modal-content hero-modal-small">
                    <div class="hero-modal-header">
                        <h2>登录状态过期</h2>
                        <span class="hero-modal-close">&times;</span>
                    </div>
                    <div class="hero-modal-body">
                        <p>登录状态已过期，您可以继续留在该页面，或者重新登录。</p>
                        <div class="hero-form-actions">
                            <button type="button" class="hero-btn hero-btn-primary" id="relogin">重新登录</button>
                            <button type="button" class="hero-btn hero-btn-secondary" id="stay-page">继续浏览</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    // 显示消息
    function showMessage(containerId, message, type = 'info') {
        const container = document.getElementById(containerId);
        if (container) {
            container.textContent = message;
            container.className = `hero-message hero-message-${type}`;
            container.style.display = 'block';
            
            // 3秒后隐藏消息
            setTimeout(() => {
                container.style.display = 'none';
            }, 3000);
        }
    }
    
    // 清空表单
    function clearForm(formId) {
        const form = document.getElementById(formId);
        if (form) {
            form.reset();
        }
    }
    
    // 模态框管理器
    const ModalManager = {
        show(modalId) {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.style.display = 'block';
                document.body.style.overflow = 'hidden';
            }
        },
        
        hide(modalId) {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.style.display = 'none';
                document.body.style.overflow = '';
                // 清空消息
                const message = modal.querySelector('.hero-message');
                if (message) {
                    message.style.display = 'none';
                }
            }
        },
        
        hideAll() {
            const modals = document.querySelectorAll('.hero-modal');
            modals.forEach(modal => {
                modal.style.display = 'none';
            });
            document.body.style.overflow = '';
        }
    };
    
    // 登录模态框组件
    const HeroLoginModal = {
        /**
         * 初始化模态框
         */
        init() {
            // 检查是否已经初始化
            if (document.getElementById('hero-login-modal')) {
                return;
            }
            
            // 创建模态框HTML
            const modalContainer = document.createElement('div');
            modalContainer.innerHTML = createModalHTML();
            document.body.appendChild(modalContainer);
            
            // 绑定事件
            this.bindEvents();
        },
        
        /**
         * 绑定事件处理程序
         */
        bindEvents() {
            // 关闭按钮事件
            document.querySelectorAll('.hero-modal-close').forEach(closeBtn => {
                closeBtn.addEventListener('click', (e) => {
                    const modal = e.target.closest('.hero-modal');
                    if (modal) {
                        ModalManager.hide(modal.id);
                    }
                });
            });
            
            // 点击模态框外部关闭
            document.querySelectorAll('.hero-modal').forEach(modal => {
                modal.addEventListener('click', (e) => {
                    if (e.target === modal) {
                        ModalManager.hide(modal.id);
                    }
                });
            });
            
            // ESC键关闭模态框
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape') {
                    ModalManager.hideAll();
                }
            });
            
            // 登录表单提交
            document.getElementById('hero-login-form').addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleLogin();
            });
            
            // 注册表单提交
            document.getElementById('hero-register-form').addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleRegister();
            });
            
            // 切换到注册
            document.getElementById('show-register').addEventListener('click', () => {
                ModalManager.hide('hero-login-modal');
                this.showRegister();
            });
            
            // 切换到登录
            document.getElementById('show-login').addEventListener('click', () => {
                ModalManager.hide('hero-register-modal');
                this.showLogin();
            });
            
            // 确认注销
            document.getElementById('confirm-logout').addEventListener('click', () => {
                this.handleLogout();
            });
            
            // 取消注销
            document.getElementById('cancel-logout').addEventListener('click', () => {
                ModalManager.hide('hero-logout-modal');
            });
            
            // 重新登录
            document.getElementById('relogin').addEventListener('click', () => {
                ModalManager.hide('hero-expired-modal');
                this.showLogin();
            });
            
            // 继续浏览
            document.getElementById('stay-page').addEventListener('click', () => {
                ModalManager.hide('hero-expired-modal');
            });
        },
        
        /**
         * 处理登录
         */
        handleLogin() {
            const form = document.getElementById('hero-login-form');
            const formData = new FormData(form);
            const username = formData.get('username');
            const password = formData.get('password');
            
            if (!username || !password) {
                showMessage('login-message', '请输入用户名和密码', 'error');
                return;
            }
            
            // 显示加载状态
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.textContent = '登录中...';
            submitBtn.disabled = true;
            
            HeroAuth.login(username, password)
                .then(data => {
                    showMessage('login-message', '登录成功！', 'success');
                    clearForm('hero-login-form');
                    
                    // 1秒后关闭模态框
                    setTimeout(() => {
                        ModalManager.hide('hero-login-modal');
                        // 触发登录成功事件
                        document.dispatchEvent(new CustomEvent('hero:loginSuccess', { detail: data }));
                        // 刷新页面或执行其他操作
                        if (this.onLoginSuccess) {
                            this.onLoginSuccess(data);
                        } else {
                            location.reload();
                        }
                    }, 1000);
                })
                .catch(error => {
                    showMessage('login-message', error.message || '登录失败', 'error');
                })
                .finally(() => {
                    submitBtn.textContent = originalText;
                    submitBtn.disabled = false;
                });
        },
        
        /**
         * 处理注册
         */
        handleRegister() {
            const form = document.getElementById('hero-register-form');
            const formData = new FormData(form);
            const username = formData.get('username');
            const password = formData.get('password');
            const confirmPassword = formData.get('confirmPassword');
            
            if (!username || !password || !confirmPassword) {
                showMessage('register-message', '请填写所有字段', 'error');
                return;
            }
            
            if (password !== confirmPassword) {
                showMessage('register-message', '两次输入的密码不一致', 'error');
                return;
            }
            
            if (password.length < 6) {
                showMessage('register-message', '密码长度至少6位', 'error');
                return;
            }
            
            // 显示加载状态
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.textContent = '注册中...';
            submitBtn.disabled = true;
            
            HeroAuth.register({ username, password })
                .then(data => {
                    showMessage('register-message', '注册成功！请登录', 'success');
                    clearForm('hero-register-form');
                    
                    // 2秒后切换到登录
                    setTimeout(() => {
                        ModalManager.hide('hero-register-modal');
                        this.showLogin();
                    }, 2000);
                })
                .catch(error => {
                    showMessage('register-message', error.message || '注册失败', 'error');
                })
                .finally(() => {
                    submitBtn.textContent = originalText;
                    submitBtn.disabled = false;
                });
        },
        
        /**
         * 处理注销
         */
        handleLogout() {
            const confirmBtn = document.getElementById('confirm-logout');
            const originalText = confirmBtn.textContent;
            confirmBtn.textContent = '注销中...';
            confirmBtn.disabled = true;
            
            HeroAuth.logout()
                .then(() => {
                    showMessage('logout-message', '注销成功', 'success');
                    
                    // 1秒后关闭模态框并刷新页面
                    setTimeout(() => {
                        ModalManager.hide('hero-logout-modal');
                        // 触发注销成功事件
                        document.dispatchEvent(new CustomEvent('hero:logoutSuccess'));
                        // 刷新页面或执行其他操作
                        if (this.onLogoutSuccess) {
                            this.onLogoutSuccess();
                        } else {
                            location.reload();
                        }
                    }, 1000);
                })
                .catch(error => {
                    showMessage('logout-message', error.message || '注销失败', 'error');
                })
                .finally(() => {
                    confirmBtn.textContent = originalText;
                    confirmBtn.disabled = false;
                });
        },
        
        /**
         * 显示登录模态框
         */
        showLogin() {
            this.init();
            clearForm('hero-login-form');
            ModalManager.show('hero-login-modal');
        },
        
        /**
         * 显示注册模态框
         */
        showRegister() {
            this.init();
            clearForm('hero-register-form');
            ModalManager.show('hero-register-modal');
        },
        
        /**
         * 显示注销确认模态框
         */
        showLogoutConfirm() {
            this.init();
            ModalManager.show('hero-logout-modal');
        },
        
        /**
         * 显示登录过期模态框
         */
        showExpiredModal() {
            this.init();
            ModalManager.show('hero-expired-modal');
        },
        
        /**
         * 设置登录成功回调
         */
        setLoginSuccessCallback(callback) {
            this.onLoginSuccess = callback;
        },
        
        /**
         * 设置注销成功回调
         */
        setLogoutSuccessCallback(callback) {
            this.onLogoutSuccess = callback;
        },
        
        /**
         * 关闭所有模态框
         */
        hideAll() {
            ModalManager.hideAll();
        }
    };
    
    // 全局暴露
    window.HeroLoginModal = HeroLoginModal;
    
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 可以在这里进行一些初始化工作
    });
    
})();